# -*- coding: utf-8 -*-
""" 
@author: ertao.xyz
@create: 2021-09-07 15:05
@description: 
"""
from typing import List
import json
from enum import Enum

from tortoise import fields
from tortoise.models import Model
from tortoise.contrib.pydantic import pydantic_model_creator

from core.model import AbstractBaseModel, TimestampMixin


class MenuType(str, Enum):
    PAGE = "PAGE"
    MENU = "MENU"
    BUTTON = "BUTTON"


class Menu(AbstractBaseModel, TimestampMixin):
    type = fields.CharEnumField(MenuType)
    name = fields.CharField(max_length=32, description='菜单名称')
    title = fields.CharField(max_length=32, description='标题', null=True)
    parent = fields.ForeignKeyField('models.Menu', null=True, description='上级菜单', related_name='children')
    orderNo = fields.IntField(description='排序', default=1, null=True)
    icon = fields.CharField(max_length=32, description='图标', null=True)
    path = fields.CharField(max_length=128, unique=True, description='路径地址', null=True)
    component = fields.CharField(max_length=128, null=True, description='组件路径')
    permission = fields.CharField(max_length=64, description='权限标识', null=True)
    status = fields.BooleanField(default=True, description='状态')
    isExt = fields.BooleanField(default=False, description='是否外链')
    show = fields.BooleanField(default=True, description='是否显示')
    redirect = fields.CharField(max_length=128, null=True, description='重定向')
    routerMeta = fields.JSONField(null=True, default=None,description='Meta 配置')

    async def to_json_menu(self, level=0, field_list: List = None):
        if self.isExt:
            pass

    async def to_json(self, level=0, field_list: List = None):
        _fields_list = field_list
        if field_list is None:
            _fields_list = self._meta.fields
        d = {}
        meta = {}
        for item in ['title', 'icon']:
            value = getattr(self, item)
            if value:
                meta[item] = value
            elif item == 'title':
                meta[item] = self.name
        try:
            meta.update(self.routerMeta)
        except:
            pass

        for field in _fields_list:
            value = getattr(self, field)
            if value is not None or field == 'parent_id':
                d[field] = getattr(self, field)
        d['meta'] = meta
        return d

    class Meta:
        table = 'menu'
        table_description = '菜单表'
        ordering = ["-orderNo", "id"]

    class PydanticMeta:
        exclude = ["created_at", "modified_at", 'id', 'is_delete']


class RoleMenu(TimestampMixin, Model):
    role = fields.ForeignKeyField('models.Role', related_name='role', to_field='value')
    menus = fields.TextField(null=True)

    class Meta:
        table = 'role_menu'
        table_description = '角色菜单表'
        # ordering = ["-orderNo", "id"]

    class PydanticMeta:
        exclude = ["created_at", "modified_at"]


MenuBase = pydantic_model_creator(Menu, name='MenuCreate')
